package com.study.controller;

import com.alibaba.fastjson.JSON;
import com.study.entity.ValidModel;
import com.study.entity.group.GroupA;
import com.study.entity.group.GroupB;
import com.study.entity.group.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;

@RestController
public class ValidController {

    @RequestMapping("/valid")
    public String valid(@RequestBody(required = false) @Valid ValidModel model,
                        BindingResult result) {
        if (result.hasErrors()) {
            for (ObjectError error : result.getAllErrors()) {
                System.out.println(error.getDefaultMessage());
            }
        }
        System.out.println(JSON.toJSONString(result.getAllErrors()));
        return "success";
    }
    /*
    requst body:
    {
        "userName":"neo",
        "age":123,
        "isFalse":"true"
    }
    127.0.0.1:8080/valid 执行
     */

    @RequestMapping("/validNoBindingResult")
    public String validNoBindingResult(@RequestBody(required = false) @Valid ValidModel model) {
        return "success";
    }

    @Autowired
    private Validator validator;

    @RequestMapping("/valid3")
    public String valid3(@RequestBody(required = false) @Valid ValidModel model){
        //System.out.println(model.toString());
        Set<ConstraintViolation<ValidModel>> violationSet = validator.validate(model);
        for (ConstraintViolation<ValidModel> model1 : violationSet) {
            System.out.println(model1.getMessage());
        }
        return "success";
    }

    @RequestMapping("/valid4")
    public String valid4(@RequestBody @Validated({GroupA.class}) Person person,
                         BindingResult result){
        if(result.hasErrors()){
            for (ObjectError error : result.getAllErrors()) {
                System.out.println(error.getDefaultMessage());
            }
        }
        System.out.println(JSON.toJSONString(result.getAllErrors()));
        return "success";
    }

    @RequestMapping("/valid5")
    public String valid5(@RequestBody(required = false) @Validated({GroupB.class, Default.class}) Person person,
                         BindingResult result){
        if(result.hasErrors()){
            for (ObjectError error : result.getAllErrors()) {
                System.out.println(error.getDefaultMessage());
            }
        }
        System.out.println(JSON.toJSONString(result.getAllErrors()));
        return "success";
    }
}